package com.kitri.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

import com.kitri.db.SetOfDataSource;
import com.kitri.domain.JuctionCoSu;

public class JuctionCoSuDaoImpl implements JuctionCoSuDao {

	@Override
	public void add(JuctionCoSu juctionCoSu) {
		StringBuffer sql = new StringBuffer();

		sql.append("INSERT INTO Juction_Co_Su ");
		sql.append("VALUES(?, ?)");

		JdbcTemplate jdbcTemplate = new JdbcTemplate(
				SetOfDataSource.getDataSource());
		if (checkIt(juctionCoSu)) {
			jdbcTemplate.update(
					sql.toString(),
					new Object[] { juctionCoSu.getCourseId(),
							juctionCoSu.getSubjectId() });
		}
	}

	@Override
	public void remove(JuctionCoSu juctionCoSu) {
		StringBuffer sql = new StringBuffer();

		sql.append("DELETE FROM Juction_Co_Su ");
		sql.append("WHERE COURSE_ID = ? ");
		sql.append("AND SUBJECT_ID = ?");

		JdbcTemplate jdbcTemplate = new JdbcTemplate(
				SetOfDataSource.getDataSource());
		jdbcTemplate.update(
				sql.toString(),
				new Object[] { juctionCoSu.getCourseId(),
						juctionCoSu.getSubjectId() });
	}

	@Override
	public List<JuctionCoSu> list() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean checkIt(JuctionCoSu juctionCoSu) {
		String sql = "SELECT * FROM Juction_Co_Su WHERE COURSE_ID = ? AND SUBJECT_ID = ?";

		final JuctionCoSu juctionObject = new JuctionCoSu();

		JdbcTemplate jdbcTemplate = new JdbcTemplate(
				SetOfDataSource.getDataSource());
		jdbcTemplate.query(sql, new Object[] { juctionCoSu.getCourseId(),
				juctionCoSu.getSubjectId() }, new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				juctionObject.setCourseId(rs.getString("COURSE_ID"));
				juctionObject.setSubjectId(rs.getString("SUBJECT_ID"));
			}
		});

		if (juctionObject.getCourseId() == null)
			return true;
		return false;
	}

	@Override
	public void removeOfCourse(String courseId) {
		StringBuffer sql = new StringBuffer();

		sql.append("DELETE FROM Juction_Co_Su ");
		sql.append("WHERE COURSE_ID = ? ");

		JdbcTemplate jdbcTemplate = new JdbcTemplate(
				SetOfDataSource.getDataSource());
		jdbcTemplate.update(
				sql.toString(),
				new Object[] { courseId });
	}

}
